<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>


      <el-form-item label="总价格" prop="totalPrice">
        <el-input
          v-model="queryParams.totalPrice"
          placeholder="请输入总价格"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>


      <el-form-item label="微信支付订单号" prop="paymentNo">
        <el-input
          v-model="queryParams.paymentNo"
          placeholder="请输入微信支付订单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>


      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['operate:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['operate:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['operate:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['operate:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange" @sort-change="changeTableSort">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户姓名" align="center" sortable="custom" v-if="columns[0].visible" prop="wuname" />
      <el-table-column label="商品名称" align="center" sortable="custom" v-if="columns[1].visible" prop="wgname" />
      <el-table-column label="取车点" align="center" sortable="custom" v-if="columns[2].visible" prop="wppname" />
      <el-table-column label="开始时间" align="center" sortable="custom" v-if="columns[3].visible" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" sortable="custom" v-if="columns[4].visible" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同图片" align="center" v-if="columns[5].visible" prop="contractImg">
        <template #default="scope">
          <image-preview :src="scope.row.contractImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="业务员合同图片" align="center" v-if="columns[6].visible" prop="staffContractImg">
        <template #default="scope">
          <image-preview :src="scope.row.staffContractImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="租赁时长" align="center" sortable="custom" v-if="columns[7].visible" prop="totalTime" />
      <el-table-column label="租金" align="center" sortable="custom" v-if="columns[8].visible" prop="totalPrice" />
      <el-table-column label="押金" align="center" sortable="custom" v-if="columns[9].visible" prop="wgdeposit" />
      <el-table-column label="已退" align="center" sortable="custom" v-if="columns[10].visible" prop="beforeRefund" />
      <el-table-column label="可退" align="center" sortable="custom" v-if="columns[11].visible" prop="refundable" />
      <el-table-column label="状态" align="center" sortable="custom" v-if="columns[12].visible" prop="status">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="refundMoney(scope.row)" v-hasPermi="['operate.order:refund']">退款</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['operate:order:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['operate:order:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="title" v-model="open" width="50vw" append-to-body :close-on-click-modal="false">
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际天数" prop="days">
          <el-input v-model="form.days" placeholder="请输入实际天数" />
        </el-form-item>
        <el-form-item label="总价格" prop="totalPrice">
          <el-input v-model="form.totalPrice" placeholder="请输入总价格" />
        </el-form-item>
        <el-form-item label="支付价格" prop="payPrice">
          <el-input v-model="form.payPrice" placeholder="请输入支付价格" />
        </el-form-item>
        <el-form-item label="微信支付订单号" prop="paymentNo">
          <el-input v-model="form.paymentNo" placeholder="请输入微信支付订单号" />
        </el-form-item>
        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker clearable
            v-model="form.payTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择支付时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否联系" prop="isContact">
          <el-select v-model="form.isContact" placeholder="请选择商品类型" clearable>
            <el-option
              v-for="dict in sys_yes_nos"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <!-- <el-input v-model="form.isContact" placeholder="请输入是否联系:0=否,1=是" /> -->
        </el-form-item>
        <el-form-item label="合同图片" prop="contractImg">
          <image-upload v-model="form.contractImg" :isShowTip="false"/>
        </el-form-item>
        <el-form-item label="业务员合同图片" prop="staffContractImg">
          <image-upload v-model="form.staffContractImg" :isShowTip="false"/>
        </el-form-item>
        <el-form-item label="合同签订时间" prop="contractSignTime">
          <el-date-picker clearable
            v-model="form.contractSignTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择合同签订时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="租赁时长" prop="totalTime">
          <el-input v-model="form.totalTime" placeholder="请输入租赁时长" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in order_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 订单退款对话框 -->
    <el-dialog title="订单退款" v-model="moneyopen" width="50vw" append-to-body :close-on-click-modal="false">
      <el-form ref="ordermoneyRef" :model="moneyform" :rules="rules" label-width="120px">
        <el-form-item label="退款金额" prop="amount">
          <el-input v-model="moneyform.amount" placeholder="请输入退款金额" />
        </el-form-item>
        <el-form-item label="退款理由">
          <el-input v-model="moneyform.remark" placeholder="请输入退款理由" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitMoneyForm">确 定</el-button>
          <el-button @click="moneyCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder, refundOrder } from "@/api/operate/order";
import { ref } from "vue";

const { proxy } = getCurrentInstance();
const { order_status, sys_yes_nos } = proxy.useDict('order_status', 'sys_yes_nos');

const columns = ref([
  { key: 0, label: `用户姓名`,prop: 'wuname', visible: true },
  { key: 1, label: `商品名称`,prop: 'wgname', visible: true },
  { key: 2, label: `取车点`,prop: 'wppname', visible: true },
  { key: 3, label: `开始时间`,prop: 'startTime', visible: true },
  { key: 4, label: `结束时间`,prop: 'endTime', visible: true },
  { key: 5, label: `合同图片`,prop: 'contractImg', visible: true },
  { key: 6, label: `业务员合同图片`,prop: 'staffContractImg', visible: true },
  { key: 7, label: `租赁时长`,prop: 'totalTime', visible: true },
  { key: 8, label: `租金`,prop: 'totalPrice', visible: true },
  { key: 9, label: `押金`,prop: 'wgdeposit', visible: true },
  { key: 10, label: `已退`,prop: 'beforeRefund', visible: true },
  { key: 11, label: `可退`,prop: 'refundable', visible: true },
  { key: 12, label: `状态`,prop: 'status', visible: true }
]);
const orderList = ref([]);
const open = ref(false);
const moneyopen = ref(false);                           // 退款弹窗
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  moneyform: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    goodsId: null,
    pickPointId: null,
    userId: null,
    couponId: null,
    startTime: null,
    endTime: null,
    days: null,
    totalPrice: null,
    payPrice: null,
    paymentNo: null,
    payTime: null,
    isContact: null,
    isContract: null,
    contractImg: null,
    staffContractImg: null,
    contractSignTime: null,
    totalTime: null,
    status: null,
    orderByColumn: null,
    isAsc: null
  },
  rules: {
    orderNo: [
      { required: true, message: "订单号不能为空", trigger: "blur" }
    ],
    goodsId: [
      { required: true, message: "商品ID不能为空", trigger: "blur" }
    ],
    pickPointId: [
      { required: true, message: "取车点不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    couponId: [
      { required: true, message: "优惠券ID不能为空", trigger: "blur" }
    ],
    days: [
      { required: true, message: "实际天数不能为空", trigger: "blur" }
    ],
    totalPrice: [
      { required: true, message: "总价格不能为空", trigger: "blur" }
    ],
    payPrice: [
      { required: true, message: "支付价格不能为空", trigger: "blur" }
    ],
    paymentNo: [
      { required: true, message: "微信支付订单号不能为空", trigger: "blur" }
    ],
    isContact: [
      { required: true, message: "是否联系:0=否,1=是不能为空", trigger: "blur" }
    ],
    isContract: [
      { required: true, message: "签订合同:0=否,1=是不能为空", trigger: "blur" }
    ],
    contractImg: [
      { required: true, message: "合同图片不能为空", trigger: "blur" }
    ],
    staffContractImg: [
      { required: true, message: "业务员合同图片不能为空", trigger: "blur" }
    ],
    totalTime: [
      { required: true, message: "租赁时长不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态:0=待支付,1=已预约,2=租赁中,3=已完成,4=已取消不能为空", trigger: "change" }
    ],
    amount: [
      { required: true, message: "退款金额不可为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, moneyform, rules } = toRefs(data);

/** 查询订单管理列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderNo: null,
    goodsId: null,
    pickPointId: null,
    userId: null,
    couponId: null,
    startTime: null,
    endTime: null,
    days: null,
    totalPrice: null,
    payPrice: null,
    paymentNo: null,
    payTime: null,
    isContact: null,
    isContract: null,
    contractImg: null,
    staffContractImg: null,
    contractSignTime: null,
    totalTime: null,
    createTime: null,
    updateTime: null,
    status: null
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.orderByColumn = null
  queryParams.value.isAsc = null
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 退款取消按钮
function moneyCancel() {
  moneyopen.value = false;
  moneyreset();
}

// 退款表单重置
function moneyreset() {
  moneyform.value = {
    orderId: null,
    remark: null,
    amount: null
  };
  proxy.resetForm("ordermoneyRef");
}

/** 退款按钮操作 */
function refundMoney(row) {
  moneyreset();
  moneyform.value.orderId = row.id;
  moneyopen.value = true;
}

/** 退款提交按钮 */
function submitMoneyForm() {
  proxy.$refs["ordermoneyRef"].validate(valid => {
    if (valid) {
      refundOrder(moneyform.value).then(response => {
        proxy.$modal.msgSuccess("退款成功");
        moneyopen.value = false;
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除订单管理编号为"' + _ids + '"的数据项？').then(function() {
    return delOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('operate/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

// 改变排序
function changeTableSort(e){
  if(e.order){
    queryParams.value.orderByColumn = e.prop
    queryParams.value.isAsc = e.order == 'descending' ? 'desc' : 'asc'
  }else{
    queryParams.value.orderByColumn = null
    queryParams.value.isAsc = null
  }
  handleQuery()
}

getList();
</script>
